import os

from alipay import AliPay
from django import http
from django.conf import settings
from django.shortcuts import render
from django.views import View

from orders.models import OrderInfo
from payment.models import Payment
from response_code import RET, RETCODE
from users.views import LoginRequired


class PaymentView(LoginRequired):
    def get(self, request, order_id):
        try:
            order = OrderInfo.objects.get(order_id=order_id)
        except Exception as e:
            return http.JsonResponse({'code': RET.PARAMERR, 'errmsg': '参数错误'})
        # 创建支付宝支付对象(到支付宝Python SDK文档查询编写方法）
        alipay = AliPay(
            appid=settings.ALIPAY_APPID,
            app_notify_url=None,  # 默认回调url
            app_private_key_path=os.path.join(os.path.dirname(os.path.abspath(__file__)), "keys/app_private_key.pem"),
            alipay_public_key_path=os.path.join(os.path.dirname(os.path.abspath(__file__)),
                                                "keys/alipay_public_key.pem"),
            sign_type="RSA2",
            debug=settings.ALIPAY_DEBUG
        )

        # 生成登录支付宝连接
        order_string = alipay.api_alipay_trade_page_pay(
            out_trade_no=order_id,  # 交易流水号
            total_amount=str(order.total_amount),  # 交易金额
            subject="美多商城%s" % order_id,  # 标题
            return_url=settings.ALIPAY_RETURN_URL,  # 前端重定向回来的地址
        )

        # 响应登录支付宝连接
        # 真实环境电脑网站支付网关：https://openapi.alipay.com/gateway.do? + order_string
        # 沙箱环境电脑网站支付网关：https://openapi.alipaydev.com/gateway.do? + order_string
        alipay_url = settings.ALIPAY_URL + "?" + order_string
        return http.JsonResponse({'code': RET.OK, 'errmsg': 'OK', 'alipay_url': alipay_url})


class PaymentStatusView(View):
    def get(self,request):
        user = request.user
        data=request.GET.dict()#后面需要用到参数字典，要把Query_dict字典转成dict
        # 获取并从请求参数中剔除sign,它是支付宝对本次支付结果的签名，不能跟剩下的数据一起做签名运算
        sign = data.pop('sign') #>>>从data中删除了sign，并返回了被删除的值，此时data为删除sign后的数据
        # 创建支付宝支付对象
        alipay = AliPay(
            appid=settings.ALIPAY_APPID, #支付宝分配给开发者的应用ID
            app_notify_url=None,
            app_private_key_path=os.path.join(os.path.dirname(os.path.abspath(__file__)), "keys/app_private_key.pem"),
            alipay_public_key_path=os.path.join(os.path.dirname(os.path.abspath(__file__)), "keys/alipay_public_key.pem"),
            sign_type="RSA2",
            debug=settings.ALIPAY_DEBUG
        )
        #验证签名是否正确
        success=alipay.verify(data,sign)
        if success:
            # 读取order_id、支付宝流水号
            order_id=data.get('out_trade_no')
            trade_id=data.get('trade_no')
            Payment.objects.create(
                order_id=order_id,
                trade_id=trade_id
                )
            # 修改订单状态为待评价
            OrderInfo.objects.filter(order_id=order_id,status=OrderInfo.ORDER_STATUS_ENUM['UNPAID']
                                     ).update(status=OrderInfo.ORDER_STATUS_ENUM['UNCOMMENT'])
            #响应trade_id给前端使用
            context={
                'order_id':order_id,
                'trade_id':trade_id,
                'username':user.username,
            }
            return render(request,'pay_success.html',context)
        else:
            return http.HttpResponseForbidden('非法请求')